package com.example.smartcitydemo.ext

import android.content.Context
import android.content.DialogInterface
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.animation.SlideInBottomAnimation
import com.example.smartcitydemo.IP
import com.example.smartcitydemo.MyApplication
import com.example.smartcitydemo.R
import com.example.smartcitydemo.bean.Line
import com.example.smartcitydemo.databinding.DialogEditBinding
import com.google.android.material.button.MaterialButton
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.lljjcoder.Interface.OnCityItemClickListener
import com.lljjcoder.bean.CityBean
import com.lljjcoder.bean.DistrictBean
import com.lljjcoder.bean.ProvinceBean
import com.lljjcoder.style.cityjd.JDCityConfig
import com.lljjcoder.style.cityjd.JDCityPicker

/**
 * @PACKAGE_NAME: com.example.smartcitydemo.ext
 * @NAME: Caleb.F
 * @DATE: 2021/11/5 14:38
 * @Email: 1919796283@qq.com
 */
/**
 *
 * @receiver ImageView
 * @param url String? 请求连接地址
 */
fun ImageView.onLoad(url: String?) {
    val imageViewUrl = "${MyApplication.sp.getString(IP, "http://124.93.196.45:10001")}$url"
    Log.d("dedef", "onLoad: $imageViewUrl")
    Glide.with(this).load(imageViewUrl).placeholder(R.drawable.loading).error(R.drawable.picfail)
        .into(this)
}

/**
 * ViewPager2初始化扩展函数
 * @receiver ViewPager2
 * @param myadpter Adapter<*>
 * @param myTab TabLayout
 * @param tabAction Function2<Tab, Int, Unit>
 */
inline fun ViewPager2.init(
    myadpter: RecyclerView.Adapter<*>,
    myTab: TabLayout,
    crossinline tabAction: (TabLayout.Tab, Int) -> Unit
) {
    adapter = myadpter
    TabLayoutMediator(myTab, this) { tab, pos ->
        tabAction.invoke(tab, pos)
    }.attach()
}

/**
 * recyclerView初始化扩展函数
 * @receiver BaseQuickAdapter<*, *>
 */
fun BaseQuickAdapter<*, *>.init() {
    animationEnable = true
    adapterAnimation = SlideInBottomAnimation()
    setEmptyView(R.layout.loading_layout)
}


fun MaterialAlertDialogBuilder.modifyInfo(
    context: Context,
    hintString: String,
    rawString: String,
    doSomething: (String) -> Unit
) {
    val inflate = LayoutInflater.from(context).inflate(R.layout.dialog_edit, null, false)
    val bind = DataBindingUtil.bind<DialogEditBinding>(inflate)
    val dialog = MaterialAlertDialogBuilder(context).apply {
        bind?.textLayout?.run {
            prefixText = ""
            suffixText = ""
            hint = hintString
            editText?.setText(rawString)
        }
        setView(inflate)
        setCancelable(false)
        setPositiveButton("确定", null)
        setNegativeButton("取消") { dialog, which ->
            dialog.dismiss()
        }
    }.show()
    dialog.run {
        getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener { view ->
            val text = bind?.textLayout?.editText?.text?.trim().toString()
            if (text.isEmpty()) {
                ToastUtils.showShort("请输入内容再修改")
            } else {
                doSomething.invoke(text)
                dismiss()
            }
        }
    }
}

/**
 * 城市选择器
 * @receiver JDCityPicker
 */
fun JDCityPicker.showJDPicker(
    context: Context,
    selected: (ProvinceBean, CityBean, DistrictBean) -> Unit,
    cancel: () -> Unit
) {
    val JDCityConfig = JDCityConfig.Builder().build().apply {
        showType = JDCityConfig.ShowType.PRO_CITY_DIS
    }
    setConfig(JDCityConfig)
    init(context)
    setOnCityItemClickListener(object : OnCityItemClickListener() {
        override fun onSelected(province: ProvinceBean, city: CityBean, district: DistrictBean) {
            selected.invoke(province, city, district)
        }

        override fun onCancel() {
            cancel.invoke()
        }
    })
    showCityPicker()
}

/**
 * 设置圆形的MaterialButton
 * @param context Context
 * @return MaterialButton
 */
fun MaterialButton.getRoundButton(): MaterialButton {
    return this.apply {
        cornerRadius = SizeUtils.dp2px(15f)
        textSize = 8f
        setPadding(0, 0, 0, 0)
        insetTop = 0
        insetBottom = 0
        elevation = 0f
    }
}

/**
 * 给layout加入Button
 * @receiver LinearLayout
 * @param list List<Line>
 */
fun LinearLayout.addMaterialButton(list: List<Line>) {
    //收集站点名并去除重复项
    val linearlayoutParams by lazy {
        LinearLayout.LayoutParams(SizeUtils.dp2px(30f), SizeUtils.dp2px(30f)).apply {
            marginStart = 4
            marginEnd = 4
        }
    }
    val stationList = list.map { it.lineName }.toSortedSet().toList()
    stationList.onEach {
        val roundButton: MaterialButton = MaterialButton(context).getRoundButton()
        roundButton.text = it.substring(0, 2)
        addView(roundButton, linearlayoutParams)
    }
}

fun EditText.onActionSearch(
    searchAction: (String) -> Unit
) {
    setOnEditorActionListener { view, actionId, event ->
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            //输入法关闭
            KeyboardUtils.hideSoftInput(view)
            val toString = view.text.trim().toString()
            if (toString.isEmpty()) {
                ToastUtils.showShort("请输入搜索内容")
            } else {
                searchAction.invoke(toString)
            }
            true
        } else {
            false
        }
    }
}